import { navigator } from '@/apis'

const state = {
  navData: [],
  levelOneIndex: null,
  // 选中数据列表
  selectList: [],
  // 筛选
  filterData: [],
  // 当前
  gotoType: '',
  gotoValue: '',
  toPage: '',
  // 是否自动获取
  focus: true
}
const mutations = {
  updateNavData(state, data) {
    state.navData = data
  },
  updateLevelOneIndex(state, index) {
    state.levelOneIndex = index
  },
  updateSelectList(state, { navIndex, value }) {
    const maxIndex = state.selectList.length - 1
    if (navIndex === undefined || maxIndex < 0) {
      state.selectList = []
    } else if (navIndex < maxIndex) {
      state.selectList = state.selectList.slice(0, navIndex + 1)
    }
    state.selectList.push(value)
  },
  updateRsetSelectList(state) {
    state.selectList = []
  },
  // 更新filterData
  updateFilterData(state, data) {
    state.filterData = data
  },
  updateGoto(state, v) {
    state.gotoType = v.gotoType
    state.gotoValue = v.gotoValue
    state.toPage = v.toPage
  },
  // 商品中心特殊处理
  updateRelevanceItemShow(state, { index, selected } = {}) {
    if (index !== undefined) {
      state.filterData[index].relevanceItemShow = selected
    }
  },
  // 更新focus
  updateFocus(state, value) {
    state.focus = value
  }
}
const actions = {
  getNavData({ commit }) {
    navigator().then(res => {
      const data = res.data || []
      const navList = data.filter((item) => {
        const showPlatform = item.showPlatform ? item.showPlatform.split(',') : []
        if (showPlatform.length === 0) {
          return true
        }
        return showPlatform.includes('mobile')
      })
      commit('updateNavData', navList)
    })
  },
  // 获取筛选数据
  getFilterData({ commit }, ajax) {
    if (ajax === undefined) {
      return
    }
    return ajax().then(res => {
      commit('updateFilterData', res.data)
    })
  }
}
const getters = {
  levelOneData(state) {
    return state.navData
  },
  levelOneIndex(state) {
    return state.levelOneIndex
  },
  selectList(state) {
    return state.selectList || []
  },
  // 选中的最后项
  lastItem(state) {
    const index = state.selectList.length - 1
    if (index < 0) {
      return {}
    } else {
      return state.selectList[index]
    }
  },
  // 是末级
  isLast(state, getters) {
    return getters.lastItem.isLast === 1
  },
  filterData(state) {
    return state.filterData
  },
  gotoType(state) {
    return state.gotoType
  },
  gotoValue(state) {
    return state.gotoValue
  },
  focus(state) {
    return state.focus
  }
}
export default {
  state,
  mutations,
  actions,
  getters,
  namespaced: true
}
